package com.password.desktop.page;

import java.awt.Color;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import org.apache.commons.lang3.StringUtils;

import com.password.desktop.UI.AbstractMovedWindow;
import com.password.desktop.UI.InputForm;
import com.password.desktop.UI.PMButton;
import com.password.desktop.UI.PMJTextField;
import com.password.desktop.exception.NoLoginException;
import com.password.desktop.service.LoginService;
import com.password.desktop.util.MessageUtil;
import com.password.desktop.util.SysUtil;
import com.password.entity.User;
import com.password.services.FileSecretService;

/**
 * 文本加密窗口
 * 
 * @author yzh
 * @date 2020年6月4日
 *
 */
public class FileEncrptWindow extends AbstractMovedWindow {

	private static final String TIP = "请点击选择导出到的文件夹...";

	File inputFile, outputFile;
	String fileName;

	private LoginService loginService = LoginService.builderLoginService();
	private FileSecretService fileSecretService = FileSecretService.getFileSecretService();

	private JDialog encrptDialog, decrptDialog;// 加密Dialog

	private static final long serialVersionUID = 1L;

	private static final int HEIGHT_WINDOW = 294; // 窗口高度
	private static final int WIDTH_WINDOW = 528; // 窗口宽度
	private static final int HEIGHT_HEAD = 32;
	private static final int HEIGHT_TITLE = 48;
	private static final int HEIGHT_SELECTED = 96;
	private static final int HEIGHT_CONTENT = 116;
	private JPanel head; // 头部容器
	JLabel logo, minW, closeW;// logo,最小化，关闭

	JLabel encrpt, decrpt;// 加密和解密按钮

	public FileEncrptWindow() {
		// 设置对话框的风格
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		initSet();
		getContentPane().add(getHead());
		getContentPane().add(getTitle("文件加密解密"));
		getContentPane().add(getSelect());
		getContentPane().add(getContent());
		this.setTitle("PM " + loginService.getCurrentUser().getUserName());
		setVisible(true);
	}

	public void initSet() {
		this.setSize(WIDTH_WINDOW, HEIGHT_WINDOW);
		super.initSet();
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}

	public static void main(String[] args) {
		new FileEncrptWindow();
	}

	public JPanel getContent() {
		JPanel jContent = new JPanel();
		jContent.setOpaque(true);
		jContent.setBackground(Color.white);
		jContent.setLayout(null);
		jContent.setVisible(true);
		jContent.setBounds(0, HEIGHT_HEAD + HEIGHT_TITLE + HEIGHT_SELECTED, WIDTH_WINDOW, HEIGHT_CONTENT);

		encrpt = new PMButton("加密", PMButton.STYLE_SUCCESS, (s) -> {
			if (inputFile == null || !inputFile.exists()) {
				MessageUtil.showMessage(FileEncrptWindow.this, "加密的文件不存在");
				return;
			}
			if (encrptDialog == null) {
				encrptDialog = new EncrptJDialog();
			}
			encrptDialog.setVisible(true);

		});
		encrpt.setBounds(62, 26, 80, 32);

		decrpt = new PMButton("解密", PMButton.STYLE_INFO, (s) -> {
			if (inputFile == null || !inputFile.exists()) {
				MessageUtil.showMessage(FileEncrptWindow.this, "解密的文件不存在");
				return;
			}
			if (decrptDialog == null) {
				decrptDialog = new DecrptJDialog();
			}
			decrptDialog.setVisible(true);
		});
		decrpt.setBounds(349, 26, 80, 32);

		jContent.add(encrpt);
		jContent.add(decrpt);

		return jContent;
	}

	/**
	 * 获取选择框组件
	 * 
	 * @author yzh
	 * @date 2020年6月5日
	 * 
	 * @return
	 */
	public JPanel getSelect() {
		JPanel jTitle = new JPanel();
		jTitle.setOpaque(true);
		jTitle.setBackground(Color.white);
		jTitle.setLayout(null);
		jTitle.setVisible(true);
		jTitle.setBounds(0, HEIGHT_HEAD + HEIGHT_TITLE, WIDTH_WINDOW, HEIGHT_SELECTED);

		JTextField jTextField = new PMJTextField();
		jTextField.setEditable(false);

		jTextField.setBounds(24, (HEIGHT_SELECTED - 32) / 2, 360, 32);

		PMButton buttom = new PMButton("请选择文件", (e) -> {
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			int showOpenDialog = fileChooser.showOpenDialog(FileEncrptWindow.this);
			if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
				inputFile = fileChooser.getSelectedFile();
				jTextField.setText(inputFile.getAbsolutePath());
			}

		});
		buttom.setBounds(384, (HEIGHT_SELECTED - 32) / 2, 120, 32);

		jTitle.add(jTextField);
		jTitle.add(buttom);
		return jTitle;
	}

	/**
	 * 标题组件
	 * 
	 * @author yzh
	 * @date 2020年6月5日
	 * 
	 * @param title
	 * @return
	 */
	public JPanel getTitle(String title) {
		JPanel jTitle = new JPanel();
		jTitle.setOpaque(true);
		jTitle.setBackground(Color.white);
		jTitle.setLayout(null);
		jTitle.setVisible(true);
		jTitle.setBounds(0, HEIGHT_HEAD, WIDTH_WINDOW, HEIGHT_TITLE);

		JLabel txt = new JLabel(title);
		txt.setForeground(Color.black);
		txt.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_TITLE);
		txt.setFont(SysUtil.FONT_DEFAULT_BLOD);
		txt.setHorizontalAlignment(SwingConstants.CENTER);

		jTitle.add(txt);

		return jTitle;
	}

	public JPanel getHead() {
		User currentUser = loginService.getCurrentUser();
		if (currentUser == null) {
			MessageUtil.showMessage(null, "未登录");
			dispose();
			new LoginWindow();
			throw new NoLoginException("未登录");
		}
		head = new JPanel();
		head.setBackground(new Color(153, 255, 204));
		head.setLayout(null);
		head.setVisible(true);
		head.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_HEAD);
		head.setForeground(Color.WHITE);
		ImageIcon imageIcon = new ImageIcon(getResoure("素材/1.gif"));
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(WIDTH_WINDOW, HEIGHT_HEAD, Image.SCALE_DEFAULT));
		JLabel backgroud = new JLabel();
		backgroud.setIcon(imageIcon);
		backgroud.setOpaque(false);
		JLabel title = new JLabel("PM " + currentUser.getUserName());
		logo = new JLabel(SysUtil.ICON_LOGO_MIDDLE);
		minW = new JLabel(SysUtil.ICON_MIN);
		closeW = new JLabel(SysUtil.ICON_CLOSE);
		backgroud.setBounds(0, 0, WIDTH_WINDOW, HEIGHT_HEAD);
		logo.setBounds(0, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		title.setBounds(HEIGHT_HEAD + 2, 0, WIDTH_WINDOW - 64, HEIGHT_HEAD);
		title.setFont(SysUtil.FONT_DEFAULT_MIN);
		minW.setBounds(WIDTH_WINDOW - 64 - 4, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		minW.setBackground(new Color(0, 0, 0, 0.3f));
		closeW.setBounds(WIDTH_WINDOW - 32, 0, HEIGHT_HEAD, HEIGHT_HEAD);
		closeW.setBackground(new Color(0, 0, 0, 0.3f));
		// 事件区域
		minW.addMouseListener(this);
		closeW.addMouseListener(this);

		head.add(logo);
		head.add(title);
		head.add(minW);
		head.add(closeW);
		head.add(backgroud);

		return head;
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (e.getSource() == minW) {
			setExtendedState(JFrame.ICONIFIED);
		} else if (e.getSource() == closeW) {
			dispose();
			new MenuWindow();
		} else if (e.getSource() == this) {
			super.mousePressed(e);
		}

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		if (e.getSource() == minW) {
			minW.setOpaque(true);
			minW.setBackground(Color.lightGray);
		} else if (e.getSource() == closeW) {
			closeW.setOpaque(true);
			closeW.setBackground(Color.lightGray);
		}

	}

	@Override
	public void mouseExited(MouseEvent e) {
		if (e.getSource() == minW) {
			minW.setOpaque(false);
			minW.setBackground(new Color(0, 0, 0, 0.3f));
		} else if (e.getSource() == closeW) {
			closeW.setOpaque(false);
			closeW.setBackground(new Color(0, 0, 0, 0.3f));
		}
	}

	public URL getResoure(String path) {
		return this.getClass().getClassLoader().getResource(path);
	}

	class EncrptJDialog extends JDialog {

		private static final long serialVersionUID = 1L;

		public EncrptJDialog() {
			super(FileEncrptWindow.this, "加密文件导出设置", true);
			this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
			// 设置对话框的宽高
			this.setSize(326, 250);
			// 设置对话框大小不可改变
			this.setResizable(false);
			// 设置对话框相对显示的位置
			this.setLocationRelativeTo(FileEncrptWindow.this);
			this.setLayout(null);
			JFileChooser fileChooser = new JFileChooser();
			JTextField jTextField = new PMJTextField();
			jTextField.setText(TIP);
			jTextField.setForeground(Color.gray);
			jTextField.setEditable(false);
			jTextField.setBounds(32, 36, 260, 32);
			jTextField.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					outputFile = null;
					if (e.getButton() == MouseEvent.BUTTON1) {
						fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
						int showOpenDialog = fileChooser.showOpenDialog(FileEncrptWindow.this);
						if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
							outputFile = fileChooser.getSelectedFile();
							jTextField.setText(outputFile.getAbsolutePath());
						}
					}
				}

			});

			InputForm inputForm = new InputForm("文件名称", JTextField.class);
			inputForm.setBounds(0, 76, 360, 48);

			// 加密，取消
			PMButton pmE = new PMButton("确定", PMButton.STYLE_PRIMARY, (e) -> {
				String text = inputForm.getText();
				if (StringUtils.isBlank(text)) {
					MessageUtil.showMessage(this, "导出的文件名称不能为空");
					return;
				}
				if (outputFile == null) {
					MessageUtil.showMessage(this, "请选择导出文件夹");
					return;
				}
				User currentUser = loginService.getCurrentUser();
				try {
					Instant now = Instant.now();
					fileSecretService.encodeFile(currentUser, inputFile, new File(outputFile, text));
					Duration dur = Duration.between(now, Instant.now());
					setVisible(false);
					MessageUtil.showMessage(FileEncrptWindow.this, "加密成功！耗时：" + dur.toMillis() + "ms");
					return;
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageUtil.showMessage(EncrptJDialog.this, "加密失败！" + e1.getMessage());
				}

			});

			pmE.setBounds(58, 164, 80, 32);

			PMButton pmCancel = new PMButton("取消", (e) -> {
				this.setVisible(false);
			});
			pmCancel.setBounds(196, 164, 80, 32);

			this.add(pmE);
			this.add(pmCancel);
			this.add(jTextField);
			this.add(inputForm);
			// 显示对话框
			this.setVisible(true);
		}

	}

	class DecrptJDialog extends JDialog {

		private static final long serialVersionUID = 1L;

		public DecrptJDialog() {
			super(FileEncrptWindow.this, "解密文件导出设置", true);
			this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
			// 设置对话框的宽高
			this.setSize(326, 250);
			// 设置对话框大小不可改变
			this.setResizable(false);
			// 设置对话框相对显示的位置
			this.setLocationRelativeTo(FileEncrptWindow.this);
			this.setLayout(null);
			JFileChooser fileChooser = new JFileChooser();
			JTextField jTextField = new PMJTextField();
			jTextField.setText(TIP);
			jTextField.setForeground(Color.gray);
			jTextField.setEditable(false);
			jTextField.setBounds(32, 36, 260, 32);
			jTextField.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					outputFile = null;
					if (e.getButton() == MouseEvent.BUTTON1) {
						fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
						int showOpenDialog = fileChooser.showOpenDialog(FileEncrptWindow.this);
						if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
							outputFile = fileChooser.getSelectedFile();
							jTextField.setText(outputFile.getAbsolutePath());
						}
					}
				}

			});

			InputForm inputForm = new InputForm("文件名称", JTextField.class);
			inputForm.setBounds(0, 76, 360, 48);

			// 加密，取消
			PMButton pmE = new PMButton("确定", PMButton.STYLE_PRIMARY, (e) -> {
				String text = inputForm.getText();
				if (StringUtils.isBlank(text)) {
					MessageUtil.showMessage(this, "导出的文件名称不能为空");
					return;
				}
				if (outputFile == null) {
					MessageUtil.showMessage(this, "请选择导出文件夹");
					return;
				}
				User currentUser = loginService.getCurrentUser();
				try {
					Instant now = Instant.now();
					fileSecretService.decodeFile(currentUser, inputFile, new File(outputFile, text));
					Duration dur = Duration.between(now, Instant.now());
					setVisible(false);
					MessageUtil.showMessage(FileEncrptWindow.this, "解密成功！耗时：" + dur.toMillis() + "ms");
					return;
				} catch (Exception e1) {
					e1.printStackTrace();
					MessageUtil.showMessage(DecrptJDialog.this, "解密失败！" + e1.getMessage());
				}

			});

			pmE.setBounds(58, 164, 80, 32);

			PMButton pmCancel = new PMButton("取消", (e) -> {
				this.setVisible(false);
			});
			pmCancel.setBounds(196, 164, 80, 32);

			this.add(pmE);
			this.add(pmCancel);
			this.add(jTextField);
			this.add(inputForm);
			// 显示对话框
			this.setVisible(true);
		}

	}

}
